/* -----------------
* brief
* 1. this is code gen by tools
* 2. for add/update/delete/query the data save in sql database
 */

package system

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"strings"
	//"github.com/mjiulee/lego/utils"
)

func (t *SysRole) ListSysRoleAll() []SysRole {
	rtlist := make([]SysRole, 0)
	lego.GetDBEngine().Table(t).Find(&rtlist)
	return rtlist
}

/* 根据id获取记录
 * -----------------
 */
func (t *SysRole) RecodeById(id int64) *SysRole {
	item := new(SysRole)
	_, err := lego.GetDBEngine().ID(id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

/* 添加
 * -----------------
 */
func (t *SysRole) AddRecode(item2add *SysRole, mi string) bool {
	// 事务添加及修改
	_, err := lego.GetDBEngine().Transaction(func(session *xorm.Session) (interface{}, error) {
		menus := strings.Split(mi, ",")
		item2add.Id = lego.UUID()
		_, errin := session.Insert(item2add)
		if errin != nil {
			session.Rollback()
			return 0, errin
		}

		for _, mid := range menus {
			midint, _ := utils.StringToInt64(mid)
			arignth := SysRoleRight{
				Id:     lego.UUID(),
				RoleId: item2add.Id,
				SType:  1,
				SId:    midint,
			}
			_, errin := session.Insert(arignth)
			if errin != nil {
				session.Rollback()
				return 0, errin
			}
		}
		return nil, nil
	})
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *SysRole) DelRecodeById(id int64) bool {
	_, err := lego.GetDBEngine().Transaction(func(session *xorm.Session) (interface{}, error) {
		item := new(SysRole)
		_, err := lego.GetDBEngine().ID(id).Delete(item)
		if err != nil {
			return nil, err
		}

		_, err = session.Where("role_id=?", id).Delete(new(SysRoleRight))
		if err != nil {
			session.Rollback()
			return 0, err
		}
		return nil, nil
	})

	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 更新
 * -----------------*/
func (t *SysRole) UpdateRecode(rc *SysRole, mi string) bool {
	_, err := lego.GetDBEngine().Transaction(func(session *xorm.Session) (interface{}, error) {
		menus := strings.Split(mi, ",")
		_, errin := session.ID(rc.Id).Update(rc)
		if errin != nil {
			return 0, errin
		}

		_, errin = session.Where("role_id=?", rc.Id).Delete(new(SysRoleRight))
		if errin != nil {
			session.Rollback()
			return 0, errin
		}
		for _, mid := range menus {
			midint, _ := utils.StringToInt64(mid)
			arignth := SysRoleRight{
				RoleId: rc.Id,
				SId:    midint,
				SType:  1,
			}
			arignth.Id = lego.UUID() + utils.RandInt64(1,99)
			fmt.Println(arignth.Id)
			_, errin := session.Insert(arignth)
			if errin != nil {
				session.Rollback()
				return 0, errin
			}
		}
		return nil, nil
	})
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}
